<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\model\concern\SoftDelete;

class CouponUserModel extends BaseModel
{
    use SoftDelete;
    protected $table='coupon_user';

    public static $fields_status = [
        ['name'=>'未使用'],
        ['name'=>'已使用'],
        ['name'=>'已过期'],

    ];


    public static $fields_type = [
        ['name'=>'平台优惠券'],
        ['name'=>'特定优惠券'],
    ];

    public static function getTypeName($type)
    {

        return '';
    }



    public function getUserIntroAttr($value,$data)
    {
        $type = $this->getAttr('type');
        if($type==-1){
            $intro = '平台通用';
        }else{
            $intro = self::getTypeName($type);
        }

//        if($type){
//            $intro = '指定商户可用';
//        }
        return $intro;
    }

    //验证优惠券是否过期
    public function checkOverDate()
    {
//        dump($this->over_date);exit;
        if(!empty($this->over_date) && $this->over_date<date('Y-m-d')){
            return true;
        }
        return false;

    }

    protected function getExpireDateAttr($value,$data)
    {
        $start_date = $this['start_date'];
        $end_date = $this['over_date'];
        if(empty($start_date) || empty($end_date)){
            return '永久有效';
        }else{
            return $start_date.'~'.$end_date;
        }
//        return  !empty($data['over_date'])?date('Y-m-d',$data['create_time']).'至'.$data['over_date']:'永久有效';
    }

    protected function getPayMoneyIntroAttr($value,$data)
    {
        $pay_money = $data['full_money']<=0?0:$data['full_money'];
        return empty($pay_money) ? '直接优惠' : '满'.$pay_money.'可用';
    }
    protected function getCouponIntroAttr($value,$data)
    {
        return '全场通用';
    }

    //过期处理
//    public function overDayCancel()
//    {
//        $this->status=2;
//        $this->save();
//    }

    public static function getCount($user_id = 0)
    {
        if(empty($user_id)){
            return 0;
        }
        $current_day = date('Y-m-d');
        $where = $whereOr = [];
        $where[] = ['uid','=',$user_id];
        $where[] = ['status','=',0];

        $whereOr[] = ['over_date','=',null] ;
        $whereOr[] = ['over_date','>=', $current_day] ;

        return self::where(['uid'=>$user_id,'status'=>0])->where(function($query)use($whereOr){
            $query->whereOr($whereOr);
        })->count();
    }

    public static function createItem(UserModel $user_model,$award_money){
        //优惠券
        $model_coupon = new CouponUserModel();
        $model_coupon->setAttrs([
            'cid' => 0,
            'name' => 'Coupons for lucky draw rewards',
            'name_ban' => 'ভাগ্যবান ড্র পুরষ্কার জন্য কুপন',
            'uid' => $user_model['id'],
            'money' => $award_money,
            'full_money' => 0,
            'status' => 0,
            'end_date' => null,
        ]);
        $model_coupon->save();

    }


    /**
     * 获取可用的代金券/优惠券
     * @param int $user_id  用户id
     * @param array $order_money 订单金额
     * @throws
     * @return array
     */
    public static function getAllUseData($user_id, array $order_money=[])
    {
        $coupon_list = $voucher_list = [];
        self::where(['uid'=>$user_id,'status'=>0])->select()->each(function($item,$index)use(&$coupon_list,&$voucher_list,$order_money){
            if(empty($item['full_money']) || $item['full_money']<=$order_money['goods_money']){
                if($item['type']==1){
                    array_push($voucher_list,$item);
                }else{
                    array_push($coupon_list,$item);
                }
            }

        });
        return [$coupon_list,$voucher_list];

    }


    /**
     * 获取数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data=[])
    {
        $activeState = $input_data['activeState']??'';
        $limit = $input_data['limit']??null;
        $where = [];

        if($activeState=='used'){ //已使用
            $where[] = ['status','>',0];
        }elseif($activeState=='usable'){ //带使用
            $where[] = ['status','=',0];
        }




//        $state = $input_data['state']??0;
//        $where[] = ['status','=',$state]; //使用状态
        isset($input_data['uid']) && $where[]=['uid','=',$input_data['uid']];
        if(app()->http->getName()=='admin'){
//            $type = $input_data['type']??0;
//            $where[] = ['type','=',$type];

            if(!empty($input_data['cid'])){
                $where[] = ['cid','=',$input_data['cid']];
            }

        }


        $model = self::with(['linkUser'])->where($where)->order('id desc')->paginate($limit);
        return $model;
    }

    //获取用户已领取过的优惠券id
    public static function getUserHasData(UserModel $user_model=null)
    {
        $data = [];
        if(empty($user_model)){
            return $data;
        }
        $data = CouponUserModel::where(['uid'=>$user_model['id'],'self_get'=>1])->column('status','cid');
        return $data;
    }

    //创建使用记录
    public static function createUse(OrderModel $orderModel,$coupon_id)
    {
        if(empty($coupon_id)){
            return;
        }
        $model_coupon = CouponModel::find($coupon_id);
        if(empty($model_coupon)) return;

        $model = new self();
        $model->setAttrs([
            'no'=>self::make_coupon_card(),
            'cond_id'=>$orderModel['id'],
            'email'=>$orderModel['email'],
            'uid'=>$orderModel['uid'],
            'cid'=>$model_coupon['id'],
            'code'=>$model_coupon['code'],
            'name'=>$model_coupon['name'],
            'img'=>$model_coupon['img'],
            'money'=>$model_coupon['money'],
            'full_money'=>$model_coupon['full_money'],
            'content'=>$model_coupon['content'],
            'status' => 1,
        ]);
        $model->save();
    }


    //领券
    public static function getCoupon(UserModel  $user_model ,array $input_data = [])
    {
        $id = $input_data['id']??0;
        if(empty($id)) throw  new \Exception('参数异常:id');
        $model_coupon = CouponModel::find($id);
        if(empty($model_coupon)) throw  new \Exception('优惠券不存在');

        $model_get = self::where(['uid'=>$user_model['id'],'cid'=>$id,'self_get'=>1])->find();
        if(!empty($model_get)) throw  new \Exception('已领取过该券,无法再次领取');
        $model = new self();
        $model->setAttrs([
            'no'=>self::make_coupon_card(),
            'uid'=>$user_model['id'],
            'cid'=>$id,
            'name'=>$model_coupon['name'],
            'img'=>$model_coupon['img'],
            'money'=>$model_coupon['money'],
            'full_money'=>$model_coupon['full_money'],
            'content'=>$model_coupon['content'],
            'over_date' =>  CouponModel::overDate($model_coupon['expire_day']), //优惠券结束日期
            'status' => 0,
            'self_get' => 1, //自己领取
        ]);
        $model->save();
    }

    public function apiFullInfo()
    {
        $linkUser = $this->getRelation('linkUser');
        return array_merge($this->apiNormalInfo(),[
            'create_time'=>$this['create_time'],

            'user_id'=>empty($linkUser)?'':$linkUser['id'],
            'user_name'=>empty($linkUser)?'':$linkUser['name'],
            'user_avatar'=>empty($linkUser)?'':$linkUser['avatar'],
        ]);
    }

    public function apiNormalInfo()
    {

        $status = $this['status'];
        $create_time = $this->getData('create_time');
        return [
            'id' => $this['id'],
            'over_date' => (string)$this['over_date'],
            'create_date' => (string)empty($create_time)?'':date('Y-m-d',$create_time),
            'type' => (string)$this['type'],
            'type_name' => (string)self::getPropInfo('fields_type',$this['type'],'name'),
            'img' => $this['img'],
            'email' => $this['email'],
            'name' => $this['name'],
            'money' => $this['money'],
            'full_money' => $this['full_money'],
            'pay_money_intro' => $this['pay_money_intro'],
            'expire_date' => $this['expire_date'],
            'user_intro' => $this['user_intro'],
            'status' => $status,
            'status_intro' => self::getPropInfo('fields_status',$status,'name'),
        ];
    }

    public function linkUser()
    {
        return $this->belongsTo(UserModel::class,'uid');
    }
}